<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require 'global_default_function.php';

function writeData($database, $data, $param, $user) {
	$datArray = [];
	foreach ($data as $keys => $value ) {
		if( $keys > 0 ) {
			$wrtData = $md5Array = explode('	', $value);
			if( count($wrtData) == 22 ) {
				$wrtData[0]    = trim($wrtData[0]); //日期
				$wrtData[1]    = trim($wrtData[1]); //账户ID
				$wrtData[2]    = trim($wrtData[2]); //账户
				$wrtData[3]    = trim($wrtData[3]); //推广计划ID
				$wrtData[4]    = trim($wrtData[4]); //推广计划
				$wrtData[5]    = trim($wrtData[5]); //推广单元ID
				$wrtData[6]    = trim($wrtData[6]); //推广单元
				$wrtData[7]    = trim($wrtData[7]); //创意ID
				$wrtData[8]    = trim($wrtData[8]); //创意标题
				$wrtData[9]    = trim($wrtData[9]); //创意描述1
				$wrtData[10]   = trim($wrtData[10]); //创意描述2
				$wrtData[11]   = trim($wrtData[11]); //访问URL
				$wrtData[12]   = trim($wrtData[12]); //关键词keywordID
				$wrtData[13]   = trim($wrtData[13]); //关键词ID
				$wrtData[14]   = trim($wrtData[14]); //关键词
				$wrtData[15]   = trim($wrtData[15]); //搜索词
				$wrtData[16]   = trim($wrtData[16]); //搜索引擎
				$wrtData[17]   = trim($wrtData[17]); //精确匹配(地域拓展)
				$wrtData[18]   = trim($wrtData[18]); //点击率
				$wrtData[19]   = trim($wrtData[19]); //展现量
				$wrtData[20]   = trim($wrtData[20]); //点击量
				$wrtData[21]   = trim($wrtData[21]); //消费
				$wrtData[22]   = cashPrice($user['rebate'], $wrtData[21]); //现金消费
				unset( $md5Array[4], $md5Array[6], $md5Array[16], $md5Array[17], $md5Array[18], $md5Array[19], $md5Array[20], $md5Array[21]);
				$md5 = md5(implode('', $md5Array));
				$index = array_search($md5, array_column($datArray, 'md5'));
				if( $index === false ) {
					array_push($datArray, [ 'userid' => $wrtData[1], 'md5' => $md5, 'data' => [
						$wrtData[0], $wrtData[1], $wrtData[2], $wrtData[3], $wrtData[4], $wrtData[5], $wrtData[6], $wrtData[12], $wrtData[13], $wrtData[14], $wrtData[15], $wrtData[19], $wrtData[20], $wrtData[21], $wrtData[22], $wrtData[7]
					]]);
				} else {
					$datArray[$index]['data'][11] += $wrtData[19]; // 展现量
					$datArray[$index]['data'][12] += $wrtData[20]; // 点击量
					$datArray[$index]['data'][13] += $wrtData[21]; // 消费
					$datArray[$index]['data'][14] += $wrtData[22]; // 现金消费
				}
			}
		}
	}
	
	$delArray = [];
	$sqlArray = [];
	$serverData = date('Y-m-d');
	foreach ($datArray as $value ) {
		if(!in_array($value['md5'], $delArray)) {
			array_push($delArray, $value['md5']);
		}
		$cpc = round($value['data'][13] / $value['data'][12], 2);// 平均点击价
		$ctr = round($value['data'][12] / $value['data'][11] * 100, 2); // 点击率
		$res = $database->query("select id, rebate from cfg_search where md5='{$value['md5']}' LIMIT 1");
		if( isset($res[0]['id']) ) {
			if( $serverData != $value['data'][0] ) {
				$user['rebate']    = $res[0]['rebate'];
				$value['data'][14] = cashPrice($res[0]['rebate'], $value['data'][13]); //现金消费
			}
			$database->query( " UPDATE cfg_search SET `customerid` = '{$user['customerid']}', `contact` = '{$user['contact']}', `bazaarId` = '{$user['bazaarId']}', `rebate` = '{$user['rebate']}', `cash` = '{$value['data'][14]}', `campaign` = '{$value['data'][4]}', `adgroup` = '{$value['data'][6]}',
				`impression` = '{$value['data'][11]}', `clicks` = '{$value['data'][12]}', `cost` = '{$value['data'][13]}', `cpc` = '{$cpc}', `ctr` = '{$ctr}' WHERE id = '{$res[0]['id']}'; ");
		} else {
			$datatime = strtotime(date("{$value['data'][0]} 01:01:01"));
			array_push($sqlArray, "( '{$user['customerid']}', '{$user['contact']}', '{$user['companyId']}', 1, '{$user['bazaarId']}', '{$user['rebate']}', '{$value['data'][14]}', 0, 0, '{$datatime}', '{$value['data'][1]}', '{$value['data'][2]}',
				'{$value['data'][3]}', '{$value['data'][4]}', '{$value['data'][5]}', '{$value['data'][6]}', '{$value['data'][7]}', '{$value['data'][9]}', '{$value['data'][10]}', '{$value['data'][11]}',
					'{$value['data'][12]}', '{$value['data'][13]}', '{$cpc}', '{$ctr}', '{$value['data'][15]}', '{$value['md5']}' )");
		}
	}

	$writeNumber = 3000;
	$writeArrayNumbers = count($sqlArray);
	for ($i = 0; $i < ceil( $writeArrayNumbers / $writeNumber ); $i++) {
		$sqlstr = array_slice($sqlArray, ($i * $writeNumber), $writeNumber);
		$database->query( 'INSERT INTO cfg_search ( `customerid`, `contact`, `companyId`, `userType`, `bazaarId`, `rebate`, `cash`, `copynumber`, `copycost`, `datatime`, `userid`, `username`, `campaignid`, `campaign`, `adgroupid`,
		  `adgroup`, `keywordid`, `keyword`, `word`, `impression`, `clicks`, `cost`, `cpc`, `ctr`, `creativeid`, `md5`) values ' . implode(',', $sqlstr) );
	}

	updateTime($database, $user, 1);

	if($param['dataType']) {
		$startData = strtotime(date("Y-m-d 00:00:00", strtotime("-{$param['dataType']} day")));
		$endData   = $startData + 86400;
	} else {
		$startData = strtotime(date("Y-m-d 00:00:00"));
		$endData   = strtotime(date("Y-m-d 00:00:00", strtotime("+1 day")));
	}

	$searchData = $database->query("SELECT `id`, `md5` FROM cfg_search where `companyId` = {$user['companyId']} and userid = {$user['userid']} and `datatime` between {$startData} and {$endData}");
	if ($searchData === false) {
		return false;
	}

	if(!is_array($searchData)) {
		return false;
	}

	$searchData = array_unique($searchData, SORT_REGULAR);
	$remoteRepeatNumber = count($delArray);
	$localRepeatNumber  = count($searchData);
	if( $localRepeatNumber > 0 && $remoteRepeatNumber > 0 && $localRepeatNumber <> $remoteRepeatNumber ) {
		if( $param['dataType'] ) {
			showMessage('本地数据'. count($searchData) .'条, 远程数据'. count($delArray) .'条, 删除' . $param['dataType'] . '前天数据' . (count($delArray) - count($searchData)) . '条. ' );
		} else {
			showMessage('本地数据'. count($searchData) .'条, 远程数据'. count($delArray) .'条, 删除今天数据' . (count($delArray) - count($searchData)) . '条. ' );
		}
		foreach ($searchData as $value) {
			if( in_array($value['md5'], $delArray ) === false ) {
				$database->query("DELETE FROM cfg_search WHERE id = {$value['id']};");
			}
		}
	}
}

run(function() use ($argv) {
	$param = [];
	$param['startDate'] = $param['endDate'] = date('Y-m-d');
	if( count($argv) == 1 ) {
		$param['dataType'] = 0;
		showMessage('读取当日搜索词数据.' );
	} else {
		$param['dataType'] = $argv[1];
		$param['endDate'] = date("Y-m-d", strtotime("-1 day"));
		$param['startDate'] = date("Y-m-d", strtotime("-{$argv[1]} day"));
		showMessage('读取' . $argv[1] . '天前到昨天搜索词数据.' );
	}

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `rebate`, `customerid`, `contact`, `bazaarId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType = 1');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

	foreach ($userList as $user) {
		go(function() use ($config, $param, $user)  {
			$database = new MySQL;
			$connect = $database->connect($config);
			if( $connect === false) {
				return;
			}
			$user['rebate'] = empty($user['rebate']) ? 0 : $user['rebate'];
			showMessage($user['username'].'请求搜索词报告数据.' );
			$reportId = getProfessionalReportId(json_encode ( [ 'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ], 'body'=> [ 'reportRequestType'=> ['performanceData'=> [ 'ctr', 'impression', 'click', 'cost' ], 'levelOfDetails'=> 12,
				'startDate'=> $param['startDate'], 'endDate'=> $param['endDate'], 'unitOfTime'=> 5, 'reportType'=> 6, 'statRange' => 3, 'attributes'=> null, 'device' => 2 ]] ] ));
			if( $reportId['code'] == 403 ) {
				showMessage($reportId['data']);
				return;
			}
			showMessage($user['username'].'读取搜索词报告状态.' );
			$reportFilePath = getReportFileUrl($user, $reportId['data']->reportId);
			if(!$reportFilePath) {
				showMessage($user['username'].'请求搜索词报告超时.' );
				return;
			}
			showMessage($user['username'].'搜索词报告下载地址: ' . $reportFilePath );
			$reportFiles = getReportFiles($reportFilePath);
			if( $reportFiles === false ) {
				updateTime($database, $user, 1);
				showMessage($user['username'].'搜索词报告暂无数据.' );
				return;
			}
			writeData($database, $reportFiles, $param, $user);
		});
		Swoole\Coroutine::sleep(0.5);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');